<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>权限管理</title>
    <style>
        .permission-list {
            margin-left: 20px;
        }
        .permission-item {
            margin-bottom: 10px;
        }
        .child-permission {
            margin-left: 30px;
        }
    </style>
</head>
<body>
<form action="${pageContext.request.contextPath}/menu/updatePermission" method="post">
    <input type="hidden" name="role_id" value="${acl_role.role_id}">
    <div class="permission-list">
        <c:forEach items="${aclPermissions}" var="menu">
            <div class="permission-item">
                <input type="checkbox" name="ids" value="${menu.perm_id}" class="parent-checkbox" <c:if test="${menu.checked}">checked</c:if>>${menu.name}
                <c:if test="${menu.children.size()>0}">
                    <div class="child-permission">
                        <c:forEach items="${menu.children}" var="child">
                            <div class="permission-item">
                                <input type="checkbox" name="perm_id" value="${child.perm_id}" class="child-checkbox" <c:if test="${child.checked}">checked</c:if>>${child.name}
                            </div>
                        </c:forEach>
                    </div>
                </c:if>
            </div>
        </c:forEach>
    </div>
    <input type="submit" value="提交">
</form>
</body>
</html>

<script>
    // 选中父菜单时全选子菜单
    document.querySelectorAll('.parent-checkbox').forEach(parentCheckbox => {
        parentCheckbox.addEventListener('change', function() {
            const childCheckboxes = parentCheckbox.closest('.permission-item').querySelectorAll('.child-checkbox');
            childCheckboxes.forEach(childCheckbox => {
                childCheckbox.checked = this.checked;
            });
        });
    });

    // 子菜单全部选中时也选择父菜单
    document.querySelectorAll('.child-checkbox').forEach(childCheckbox => {
        childCheckbox.addEventListener('change', function() {
            const parentCheckbox = this.closest('.permission-item').querySelector('.parent-checkbox');
            const childCheckboxes = parentCheckbox.closest('.permission-item').querySelectorAll('.child-checkbox');
            const allChecked = Array.from(childCheckboxes).every(checkbox => checkbox.checked);
            parentCheckbox.checked = allChecked;
            parentCheckbox.indeterminate = !allChecked && Array.from(childCheckboxes).some(checkbox => checkbox.checked);
        });
    });
</script>
